articles

Home / DeveloperSection / Articles / AngularJs Controllers

AngularJs Controllers

Sumit Kesarwani6522 30-Aug-2014

In this article, I’m explaining the controller concept in angularjs.

In Angular, a Controller is a JavaScript constructor function that is used to augment the Angular Scope

When a Controller is attached to the DOM via the ng-controller directive, Angular will instantiate a new Controller object, using the specified Controller's constructor function. A new child scope will be available as an injectable parameter to the Controller's constructor function as $scope.

Use controllers to:

1.     Set up the initial state of the $scope object.

2.     Add behavior to the $scope object.


The ngController directive attaches a controller class to the view. This is a key aspect of how angular supports the principles behind the Model-View-Controller design pattern.

MVC components in angular:

Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties are accessed through bindings.

View — The template (HTML with data bindings) that is rendered into the View.

Controller — The ngController directive specifies a Controller class; the class contains business logic behind the application to decorate the scope with functions and values.

Example

First create an asp.net web application and add a webform to it:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="AngularJsController.WebForm1" %>
 
<!DOCTYPE html>
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
    <script>
        function personController($scope) {
            $scope.person = {
                firstname: "",
                lastname: ""
            }
 
            $scope.greet = function () {
                alert($scope.person.firstname + " " + $scope.person.lastname);
            }
        }        
 
    </script>
</head>
<body>
        <div ng-app="" ng-controller="personController">
            <p>Enter Your Name :
                <input type="text" ng-model="person.firstname" /></p>
            <p>Enter Your Name :
                <input type="text" ng-model="person.lastname" /></p>
            <p>Fullname : {{ person.firstname + " " + person.lastname }}</p>
            <p><input type="button" value="Greet" ng-click="greet()"/></p>
        </div>
</body>
</html>

Output

Now run the application

AngularJs Controllers

 

Type firstname and lastname and both of them will come in full name

AngularJs Controllers

And when click on Greet button – it will give a message like this:

AngularJs Controllers

 

 


Leave Comment

Comments

Liked By